﻿using System;
using System.Collections.Generic;

using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WeigherMoudel
{
    public class TimerOutThread
    {
        bool isStart = false;
        DateTime lastdatetime = new DateTime();
        int timeoutmilsenconds = 5000;
        public event Action StateChanged;

        public TimerOutThread(UdpClient udpClient,  int Circlemilsenconds=500)
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    if (isStart)
                    {
                        if (DateTime.Now - lastdatetime > TimeSpan.FromMilliseconds(timeoutmilsenconds))
                        {
                            udpClient.Close();
                            StateChanged?.Invoke();
                            //Console.WriteLine("线程终止");
                            break;
                        }
                    }
                    Thread.Sleep(Circlemilsenconds);
                }
            }, TaskCreationOptions.LongRunning);
        }

        public void StartListen(int timeoutmilsenconds)
        {
            timeoutmilsenconds = 5000;
            lastdatetime = DateTime.Now;
            isStart = true;
        }

        public void EndListen()
        {
            isStart = false;
        }
    }
}
